<!--
 * @Descripttion: 
 * @version: 
 * @Author: ybac
 * @Date: 2022-10-31 17:46:47
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-07-03 15:59:32
-->
<template>
  <j-modal
    :visible.sync="modal.visible"
    :width="1200"
    :title="modal.title"
    :fullscreen.sync="modal.fullscreen"
    :switchFullscreen="modal.switchFullscreen"
    @cancelVisible="cancel"
    :footer="null"
  >
    <div class="home-wrap" style="position:relative">
      <div style="padding: 24px 0 0 24px">
        <a-row :gutter="[48, 8]">
            <a-col :span="6"><span class="title">角色编号：</span>{{ roleInfo.roleCode }}</a-col>
            <a-col :span="6"><span class="title">角色名称：</span>{{ roleInfo.roleName }}</a-col>
          </a-row>

      </div>
      <div>
        <a-card :bordered="false" class="jek-card" style="height: calc(100vh - 205px)">
          <a-button @click="handleShowFilter" icon="filter"
            >筛选 <span class="filter-num" style="margin-left: 5px">{{ ' ' + filteredNums }}</span></a-button
          >
          <a-button @click="showColumn" icon="unordered-list" class="btns">设置列</a-button>
          <div class="right-btn">
          <a-button type="primary" style="margin-right: 10px" @click="onClickAdd">关联用户</a-button>
        </div>
          <a-table
            row-key="id"
            :key="tableKey"
            size="small"
            :scroll="{ x: '500px', y: 'calc(100vh - 345px)' }"
            :hideDefaultSelections="false"
            :columns="columns"
            :dataSource="tableData"
            :pagination="false"
            @change="tableChange"
            :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange, fixed: true }"
            :components="drag(columns, 'USER_MANAGEMENT_TABLE')"
            class="jek-table"
            :loading="loadingTable"
          >
            <div slot="actions" slot-scope="text, record">
              <a-button type="link" @click="onRemove(record.id)">移除</a-button>
              <!-- <a-popconfirm style="z-index:99999" placement="top" ok-text="确认" cancel-text="取消" @confirm="onRemove(record.id)">
                <template slot="title">
                  <span>确定移除吗？</span>
                </template>
                <a-button type="link">移除</a-button>
              </a-popconfirm> -->
            </div>
            <!-- 输入框搜索 -->
            <div slot="searchInput" slot-scope="{ column }" class="searchWorkOreder">
              <a-input
                placeholder="请输入"
                v-model="filterForm[column.searchKey]"
                style="width: 188px; display: block"
                @pressEnter="handleFilter(filterForm)"
              />
              <a-button
                type="primary"
                style="width: 80px; margin-left: 20px; display: block"
                @click="handleFilter(filterForm)"
              >
                搜索
              </a-button>
            </div>
            <a-icon
              slot="searchIcon"
              slot-scope="filtered"
              type="search"
              :style="{ color: filtered ? '#108ee9' : undefined }"
            />
          </a-table>
          <SetColumn
            columnName="设置列"
            ref="SetColumn"
            v-if="showSetColumn"
            @sureBtn="sureBtn"
            @cancelBtn="showSetColumn = false"
          />
        </a-card>
      </div>
      <search-modal ref="searchModal" @handleFilter="handleFilter" :roleList="roleList"></search-modal>
      <div
        class="uni-card border"
        :style="{
          position: 'absolute',
          bottom: 0,
          right: 0,
          zIndex: 2,
          left: 0,
          background: '#fff',
          paddingLeft: '43px',
        }"
      >
        <div style="display: inline-block">
          <a-checkbox
            :indeterminate="listIndeterminate"
            :checked="listCheckAll"
            @change="onCheckAllChange"
          ></a-checkbox>
          <span style="margin-left: 8px">
            <span class="btn-text" style="margin: 0 18px" @click="onRemoveBatch">批量移除</span>
            {{ `已选 ${selectedRowKeys.length}/${pagination.total} 条` }}
          </span>
          <span class="btn-text" @click="clearArr" style="margin: 0 10px">清空</span>
        </div>
        <div style="display: inline-block; float: right">
          <a-pagination
            :total="pagination.total"
            v-model="pagination.current"
            :page-size-options="pagination.options"
            :page-size="pagination.pageSize"
            @change="onChangePage"
            @showSizeChange="onChangePage"
            show-quick-jumper
            show-size-changer
          />
        </div>
      </div>
    </div>
    <j-select-user-by-dep-jke :filter="selectedUsers" store="id" ref="JSelectUserByDep" @change="selectUser" :showInput="false" />
  </j-modal>
</template>

<script>
import { getNewColumns } from '@/utils/util'
import SetColumn from '@/pubComponent/SetColumn.vue'
import tableDragResize from '@/mixins/tableDragResize'
import moment from 'moment'
import searchModal from './searchModal.vue'
import { columnsValue } from './column'
import { mapState } from 'vuex'
import { getAction, deleteAction, postAction, putAction } from '@/api/manage'
const actionArr = [
  {
    fixed: 'right',
    title: '操作',
    width: 150,
    dataIndex: 'actions',
    ellipsis: true,
    scopedSlots: { customRender: 'actions' },
  },
]
export default {
  name: 'userList',
  mixins: [tableDragResize],
  components: {
    SetColumn,
    searchModal,
  },
  data() {
    return {
      modal: {
        title: '角色用户',
        visible: false,
        fullscreen: false,
        switchFullscreen: true,
      },
      moment,
      tableKey: 1.9,
      columnsValue,
      columns: JSON.parse(JSON.stringify(columnsValue)),
      tableData: [],
      pagination: {
        current: 1,
        pageSize: 10,
        options: ['10', '20', '30', '40', '50'],
        total: 0,
      },
      filterForm: {},
      sortForm: {},
      showSetColumn: false,
      selectedRowKeys: [],
      selectedRows: [],
      listCheckAll: false,
      listIndeterminate: false,
      loadingTable: false,
      tenantData: [],
      tenantId: '',
      departId: '',
      roleList: [],
      roleInfo: {},
      selectedUsers: ''
    }
  },
  created () {
     this.tenantId = this.$store.getters.tenantid
    var oldValue = localStorage.getItem(this.BUSI_CONST.Entity.USER_MANAGEMENT_TABLE)
    this.columns = getNewColumns(this.columnsValue, JSON.parse(oldValue), actionArr, this.columns)
  },
  computed: {
    ...mapState({
      collapsed: (state) => state.user.collapsed,
    }),
    filteredNums() {
      let nums = 0
      for (let key in this.filterForm) {
        if (this.filterForm[key]) {
          nums += 1
        }
      }
      return nums
    },
    scrollX() {
      let xnum = 0
      for (let item of this.columns) {
        xnum += Number(item.width) || 0
      }
      return xnum
    },
  },
  methods: {
    open(obj) {
      this.roleInfo = obj
      this.modal.visible = true
      this.requestData()
    },
    // 关闭表单
    cancel() {
      this.loadingForm = false
      this.modal.visible = false
    },
    // 移除
    onRemove(userids) {
      let that = this
      that.$antdConfirm({
        title: '请确定要移除吗?',
        content: ``,
        onOk() {
          deleteAction('/sys/role/deleteUserRoleBatch', { userids, roleid: that.roleInfo.id }).then(
            (res) => {
              if (res.code == 200) {
            that.$antdMessage.success('移除成功！')
            if (that.tableData.length === 1) {
              that.pagination.current = that.pagination.current == 1 ? 1 : that.pagination.current - 1
            }
            that.clearArr()
            that.requestData()
            that.$emit('success')
          } else {
            that.$antdMessage.error(res.message)
          }
            }
          )
        },
        onCancel() {},
      })
    },
    onRemoveBatch() {
      //批量移除
      if (this.selectedRowKeys.length == 0) {
        this.$antdMessage.info('请选择数据！')
        return
      }
      let that = this
      that.$antdConfirm({
        title: '请确定要移除吗?',
        content: `共选中${that.selectedRowKeys.length}条信息`,
        onOk() {
          deleteAction('/sys/role/deleteUserRoleBatch', { userids: that.selectedRowKeys.join(','), roleid: that.roleInfo.id }).then(
            (res) => {
              if (res.code == 200) {
                that.clearArr()
                that.pagination.current = 1
                that.requestData()
                that.$emit('success')
                that.$antdMessage.success('移除成功！')
              } else {
                that.$antdMessage.error(res.message)
              }
            }
          )
        },
        onCancel() {},
      })
    },
    onClickAdd() {
      this.$refs.JSelectUserByDep.onSearchDepUser()
    },
    selectUser(v) {
      console.log('选择的用户：',v);
      if (v) {
        postAction('/sys/user/addSysUserRole',{roleId: this.roleInfo.id,userIdList:v.split(',')})
          .then(res => {
            if (res.code == 200) {
              this.$antdMessage.success(res.message)
              this.$emit('success')
              this.requestData()
            }
          })
      }
    },
    // 查
    requestData() {
      this.loadingTable = true
      let params = {
        roleIds: this.roleInfo.id,
        pageNo: this.pagination.current,
        pageSize: this.pagination.pageSize,
        ...this.filterForm,
      }
      getAction('/sys/role/queryUserByRoleid', params)
        .then((res) => {
          if (res.code == 200) {
            this.tableData = res.result.records || []
            setTimeout(() => {
              this.tableKey += 1
              this.loadingTable = false
            }, 1000);
            let arr = []
            this.tableData.forEach(item => {
              arr.push(item.id)
            })
            this.selectedUsers = arr.join(',')
            this.pagination.total = res.result.total
          } else {
            this.$antdMessage.error(res.message)
            this.loadingTable = false
          }
        })
        .catch((err) => {
          this.loadingTable = false
          console.log(err)
        })
    },
    // 排序
    tableChange(pagination, filters, sorter, { currentDataSource }) {
      this.current = 1
      if (sorter.order) {
        let sortType = ''
        if (sorter.order == 'ascend') {
          sortType = 'ASC'
        } else {
          sortType = 'DESC'
        }
        this.sortForm = {
          sortType: sortType,
          sortColumn: sorter.columnKey,
        }
        this.requestData()
      } else {
        this.sortForm = {
          sortType: '',
          sortColumn: '',
        }
        this.requestData()
      }
    },
    // 筛选
    handleShowFilter() {
      this.$refs.searchModal.openFilter(this.filterForm)
    },
    handleFilter(form) {
      console.log('form是怎样：', form)
      this.pagination.current = 1
      this.filterForm = JSON.parse(JSON.stringify(form))
      this.requestData()
    },
    // 分页
    onChangePage(current, pageSize) {
      this.pagination.current = current
      this.pagination.pageSize = pageSize
      this.requestData()
    },
    /* 打开设置列面板 */
    showColumn() {
      this.showSetColumn = true
      this.$nextTick(() => {
        this.$refs.SetColumn.paramsData(this.columnsValue, this.BUSI_CONST.Entity.USER_MANAGEMENT_TABLE, this.columns)
      })
    },
    /* 设置列 */
    sureBtn(emitArr) {
      localStorage.setItem(this.BUSI_CONST.Entity.USER_MANAGEMENT_TABLE, JSON.stringify(emitArr))
      this.columns = getNewColumns(this.columnsValue, emitArr, actionArr)
      this.tableKey += 1
    },
    // table选择
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      this.checkBoxStatus()
    },
    // 底部全选
    onCheckAllChange(e) {
      if (e.target.checked) {
        for (let item of this.tableData) {
          this.selectedRowKeys = this.selectedRowKeys.filter((each) => {
            return each != item.id
          })
          this.selectedRowKeys.push(item.id)

          this.selectedRows = this.selectedRows.filter((each) => {
            return each.id != item.id
          })
          this.selectedRows.push(item)
        }
      } else {
        for (let item of this.tableData) {
          this.selectedRowKeys = this.selectedRowKeys.filter((each) => {
            return each != item.id
          })
          this.selectedRows = this.selectedRows.filter((each) => {
            return each.id != item.id
          })
        }
      }
      this.checkBoxStatus()
    },
    // 底部清空
    clearArr() {
      this.selectedRowKeys = []
      this.selectedRows = []
      this.checkBoxStatus()
    },
    checkBoxStatus() {
      if (this.selectedRowKeys.length == 0) {
        this.listIndeterminate = false
        this.listCheckAll = false
      } else {
        let tableIds = []
        for (let item of this.tableData) {
          tableIds.push(item.id)
        }
        let checkValue = this.isInclude(tableIds, this.selectedRowKeys)
        if (checkValue) {
          this.listIndeterminate = false
          this.listCheckAll = true
        } else {
          this.listIndeterminate = true
          this.listCheckAll = false
        }
      }
    },
    isInclude(aa, bb) {
      return aa.every((item) => {
        return bb.some((sub) => {
          return sub === item
        })
      })
    },
  },
}
</script>

<style lang="less" scoped>
@import '~@/assets/less/public.less';
.flex(@jc,@ai,@fd:row) {
  display: flex;
  justify-content: @jc;
  align-items: @ai;
  flex-direction: @fd;
}
.flex-box {
  display: flex;
}
.searchWorkOreder {
  .flex(flex-start, center);
  padding: 8px;
}
.btns {
  margin-left: 10px;
}
.right-btn {
 float: right;
  display: flex;
  justify-content: flex-end;
  margin-bottom: 16px;
}
/deep/.ant-modal-body {
  padding: 0;
}
.border {
  border-top: solid 1px #eee;
  line-height: 32px;
}
/deep/.ant-modal-wrap {
  z-index: 1000!important;
}
/deep/.ant-modal-mask {
  z-index: 1000!important;
}
</style>
